import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar styles

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  console.log(from.path, to.path, to.meta)
  // start progress bar
  NProgress.start()

  // set page title
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // determine whether the user has logged in
  console.log(1)
  if (store.getters.access_token) {
    console.log(2)
    if (to.path === '/login') {
      console.log(3)
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      console.log(4)
      // determine whether the user has obtained his permission roles through getInfo
      console.log(store.getters.roles)
      if (store.getters.roles.length === 0) {
        try {
          console.log(5)
          store.dispatch('GetMenu').then(() => {
            console.log(store.getters.menus)
            store.getters.menus.forEach(r => router.addRoute(r))
            // hack method to ensure that addRoutes is complete
            // set the replace: true, so the navigation will not leave a history record
            next({ ...to, replace: true })
          })

          // get user info
          store.dispatch('GetUserInfo').then((res) => {
            // console.log("GetUserInfo: menus", store.getters.menus);
            next({ ...to, replace: true })
          }).catch((err) => {
            console.log('error', err, to)
            console.error(!err ? '操作异常' : err.data ? err.data.message || '操作失败' : err.message || '操作异常')
            store.dispatch('FedLogOut').then(() => {
              next('/login')
            })
            NProgress.done()
          })
        } catch (error) {
          // console.log('resetToken')
          // remove token and go to login page to re-login
          // await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        console.log(6)
        next()
      }
    }
  } else {
    /* has no token */
    if (to.meta.isAuth === false) {
      next()
    } else {
      next('/login')
    }
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
